package com.siebre.picclife.asynctask.springcontext;

import java.util.Arrays;

import org.springframework.beans.factory.config.ConstructorArgumentValues;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.GenericBeanDefinition;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.type.AnnotationMetadata;

import com.google.common.base.Function;
import com.google.common.base.Predicate;
import com.google.common.collect.FluentIterable;
import com.siebre.picclife.asynctask.springcontext.annotation.ActivateAnnotatedTaskHandler;
import com.siebre.picclife.asynctask.springcontext.annotation.ActivateAsyncTask;

/**
 * 
 * @author ZhangChi
 * @since 2015年4月13日
 *
 */
public class AnnotatedTaskHandlerRegistrarBeanRegistrar implements ImportBeanDefinitionRegistrar {
	
	public void registerBeanDefinitions(
			final AnnotationMetadata importingClassMetadata,
			BeanDefinitionRegistry registry) {
		

		String packageName = FluentIterable
				.from(Arrays.<Class<?>>asList(ActivateAnnotatedTaskHandler.class, ActivateAsyncTask.class))
				.filter(new Predicate<Class<?>>() {
		
					public boolean apply(Class<?> input) {
						return importingClassMetadata.hasAnnotation(input.getName());
					}
				})
				.transform(new Function<Class<?>, String>() {
		
					public String apply(Class<?> input) {
						return (String) importingClassMetadata.getAnnotationAttributes(input.getName()).get("value");
					}
				})
				.first().orNull();

		if (packageName != null) {
			
			GenericBeanDefinition beanDefinition = new GenericBeanDefinition();
			beanDefinition.setBeanClass(AnnotatedTaskHandlerRegistrar.class);
			ConstructorArgumentValues constructorArgumentValues = new ConstructorArgumentValues();
			constructorArgumentValues.addGenericArgumentValue(packageName);
			beanDefinition.setConstructorArgumentValues(constructorArgumentValues);
			registry.registerBeanDefinition("annotatedTaskHandlerRegistrar", beanDefinition);
		}
	}
}